<template>
	<div>
		<div class="bgimg">
			<img src="../static/di tu san/di-tu-zuoshang.jpeg" alt="" class="bg one" />
			<img src="../static/di tu san/di-tu-xia.jpeg" alt="" class="bg two" />
			<img src="../static/di tu san/di-tu- you.jpeg" alt="" class="bg three" />
		</div>

		<!-- main 区域 -->
		<div class="main">
			<div class="header">
				<div v-for="(item, index) in btns" :key="index" class="btn" :class="{ active: current === index }"
					@click="currentToogle(index)">
					<img :src="`../static/images/${item.icon}.png`" class="icon" alt="" />
					{{ item.name }}
				</div>
				<div class="total">共{{ total }}条</div>
			</div>
			<div class="center">
				<div class="card">
					<div class="screeningList">
						<div class="item" v-for="(item, key, index) in screeningList" :key="index" @click="screeningClick(key)">
							<block v-if="item.type !== 'radio'">
								{{ form[key] || item.label }}
								<img class="icon" src="../static/images/yixiangchengshi.png" alt="" />
							</block>
							<u-checkbox-group v-else v-model="allSelect" placement="column" :size="16" shape="circle"
								iconPlacement="right" @change="handleChange($event, true)">
								<u-checkbox :customStyle="{ marginBottom: '8px' }" label="全选" name="1" class="allSelect"></u-checkbox>
							</u-checkbox-group>
						</div>
					</div>
				</div>
				<scroll-view :scroll-top="scrollTop" :scroll-y="true" class="tbody" @scrolltolower="scrolltolower"  @scroll="scroll">
					<div class="list">
						<div class="cardItem" v-for="(item, index) in list" :key="item.id">
							<div class="title">
								{{ index + 1 }}、{{ item.companyName1 }}
								<u-checkbox-group v-model="item.statuss" placement="column" :size="16" shape="circle" iconPlacement="right"
									@change="handleChange">
									<u-checkbox :customStyle="{ marginBottom: '8px' }" name="1" class="allSelect"></u-checkbox>
								</u-checkbox-group>
							</div>
							<div class="content2" v-for="(v, i) in contentLabelList" :key="i">
								<div class="item" v-if="!(v['length'] && v.length > 0)">
									<div class="label">{{ v.label }}</div>
									<div class="value">
										{{ item[v.value] }}
									</div>
								</div>
								<div class="item line" v-else>
									<div class="item" v-for="(j, l) in v" :key="l">
										<div class="label">{{ j.label }}</div>
										<div class="value">{{ item[j.value] }}</div>
									</div>
								</div>
							</div>
							<div class="footer">
								<div class="textBox">
									<div class="label">截至时间：</div>
									<div>{{ item.recruitmentEndTime }}</div>
								</div>
								<div class="btn">
									<u-button type="primary" text="立即投递" size="mini" @click="sendResume(item.id, true)"></u-button>
								</div>
							</div>
						</div>
					</div>
				</scroll-view>
			</div>
		</div>
		<!-- <cityPicker :cityShow="cityShow" :format="format" @confirm="confirm($event, 'intentionCity')"
			@cancel="cityShow = false"></cityPicker> -->
		<u-picker :show="cityShow" ref="Picker" :columns="cityList" @confirm="confirm($event, 'workLocation')" keyName="label"
			@cancel="cityShow = false"></u-picker>
		<u-picker :show="natureShow" ref="Picker" :columns="natureList" @confirm="confirm($event, 'companyNature')" keyName="label"
			@cancel="natureShow = false"></u-picker>
		<u-picker :show="departmentsShow" :columns="departmentsList" @confirm="confirm($event, 'recruitmentDepartment')" keyName="label"
			@cancel="departmentsShow = false"></u-picker>
		<u-toast ref="uToast"></u-toast>
		<u-popup :show="allDelivery" mode="center" title="投递列表" :customStyle="{borderRadius: '8rpx', padding: '32rpx'}">
			<div class="allDelivery">
				<scroll-view :scroll-y="true" class="list">
					<div class="item">
						<div class="label">可以投递的个数：<div class="value">{{ meetId.length }}个</div></div>
					</div>
					<div class="item">
						<div class="label">学历不符合要求的 ({{ EduNotMeet.length || 0 }})：</div>
						<div class="value" v-for="(item, index) in EduNotMeet" :key="index">{{ `${index+1}、${item}` }}</div>
					</div>
					<div class="item">
						<div class="label">专业不符合要求的 ({{ majorNotMeet.length || 0 }})：</div>
						<div class="value" v-for="(item, index) in majorNotMeet" :key="index">{{ `${index+1}、${item}` }}</div>
					</div>
				</scroll-view>
			</div>
			<div class="confirmButtonbtns">
				<u-button type="primary" :plain="true" text="取消" @click="allDeliveryClose"></u-button>
				<u-button type="primary" text="继续投递" @click="sendResume(meetId.join(','))"></u-button>
			</div>
		</u-popup>
		<u-popup :show="uploadModel" mode="center" :customStyle="{borderRadius: '8rpx', padding: '32rpx'}" @close="uploadModelClose">
			<div class="uploadModel">
				<u-button type="primary" text="点击上传" @click="onDiscernHandle"></u-button>
			</div>
		</u-popup>
	</div>
</template>

<script>
	import cityPicker from "@/components/cityPicker/index";
	import { resumeList, sendResume, delivery } from '@/api/detail/detail.js'

	export default {
		components: {
			cityPicker,
		},
		data() {
			return {
				uploadModel: false,
				allDelivery: false,
				scrollTop: 0,
				cityShow: false, // 城市picker
				departmentsShow: false, // 部门picker
				natureShow: false, // 性质picker
				current: 0,
				format: ["province"],
				cityList: [
					[{ label: '不限', value: '' }]
				],
				departmentsList: [
					[{ label: '不限', value: '' }]
				],
				natureList: [
					[{ label: '不限', value: '' }]
				],
				contentLabelList: [{
						label: "招聘岗位：",
						value: "position",
					},
					{
						label: "招聘部门：",
						value: "recruitmentDepartment",
					},
					[{
							label: "工作地点：",
							value: "workLocation",
						},
						{
							label: "单位性质：",
							value: "companyNature",
						},
					],
				],
				list: [],
				btns: [{
						icon: "toudi",
						name: "简历投递"
					},
					{
						icon: "daochu",
						name: "导出PDF"
					},
				],
				screeningList: {
					workLocation: {
						label: "意向城市",
						type: "cityPicker",
					},
					companyNature: {
						label: "单位性质",
						list: [],
					},
					recruitmentDepartment: {
						label: "招聘部门",
						list: [],
					},
					selectAll: {
						label: "全选",
						type: "radio",
					},
				},
				allSelect: [],
				form: {
					workLocation: "",
					companyNature: "",
					recruitmentDepartment: "",
					selectAll: false,
				},
				formPickerMap: {
					workLocation: "cityShow",
					companyNature: "natureShow",
					recruitmentDepartment: "departmentsShow",
				},
				total: 0,
				flag: false,
				pageNum: 1,
				one: false,
				old: {
					scrollTop: 0
				},
				query: {},
				selectArr: [],
				userInfo: {},
				compList: [
					{label: "不限", value: 0},
					{label: "国家机关", value: 1},
					{label: "央企", value: 2},
					{label: "国企", value: 3},
					{label: "事业单位", value: 4},
					{label: "民营企业", value: 5},
					{label: "上市公司", value: 6}
				],
				EduNotMeet: [], // 学历不符合要求的
				majorNotMeet: [], // 专业不符合要求的
				meetId: [],
				fileList: [],
			};
		},
		onLoad() {
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.userInfo = JSON.parse(userInfo)
			}
			const query = uni.getStorageSync('formData') || {}
			this.query = JSON.parse(query);
			this.operLog();
		},
		methods: {
			leftClick() {
				uni.navigateBack({
					delta: 1,
				});
			},
			isIos() {
				let u = navigator.userAgent
				let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
			
				if (isIOS) {
					return true
				} else {
					return false
				}
			},
			async operLog(flag = false) {
				if (this.flag) return;
				this.flag = true;
				try {
					if (!flag) this.pageNum = 1;
					const params = {
						pageNum: this.pageNum,
						pageSize: 10,
						...this.query
					};
					for (let key in this.form) {
						if (key !== 'selectAll' && this.form[key] !== '') {
							if (key == 'companyNature') {
								const num = this.natureList[0].find(v => v.label === this.form[key]).value;
								if (num || num === 0) params[key] = num
							} else {
								params[key] = this.form[key]
							}
						}
					}
					params.householdRegistration = encodeURIComponent(params.householdRegistration || '')
					if (flag) {
						if (this.list.length >= this.total) return this.flag = false;
						this.pageNum++;
						const { data } = await resumeList(params);
						data.dataTable.rows = data.dataTable.rows.map(v => ({ ...v, statuss: [] }))
						this.list = [...this.list, ...data.dataTable.rows];
						this.allSelect = []
					} else {
						const { data } = await resumeList(params);
						this.total = data.dataTable.total;
						data.dataTable.rows = data.dataTable.rows.map(v => ({ ...v, statuss: [] }))
						this.list = data.dataTable.rows;
						if (!this.one) {
							this.cityList[0].push(...data.workLocationSet.map((v, i) => ({ label: v, value: i })));
							this.natureList[0].push(...data.companyNatureSet.map((v, i) => {
								const vIndex = this.compList.find(item => item.label === v);
								return { label: v, value: vIndex.value }
							}));
							this.departmentsList[0].push(...data.recruitmentDepartmentSet.map((v, i) => ({ label: v, value: i })));
							this.one = true;
						}
						this.scrollTop = this.old.scrollTop
						this.$nextTick(function() {
							this.scrollTop = 0
            });
						this.pageNum++;
					}
					this.flag = false;
				} catch (err) {
					this.flag = false;
				}
			},
			scrolltolower() {
				this.operLog(true)
			},
		 	async currentToogle(num) {
				const query = {
					...this.query
				}
				if (this.selectArr.length > 0) {
					query.ids = this.selectArr.join(',')
				}
				if (num === 0) {
					if (this.selectArr.length <= 0) {
						uni.showToast({
							title: '请选择要投递的岗位',
							icon: 'none'
						})
						return
					}
					this.sendResume(this.selectArr.join(','), true)
				} else {
					for (let key in this.form) {
						if (key !== 'selectAll' && this.form[key] !== '') {
							if (key == 'companyNature') {
								const num = this.natureList[0].find(v => v.label === this.form[key]).value;
								if (num || num === 0) query[key] = num
							} else {
								query[key] = this.form[key]
							}
						}
					}
					uni.navigateTo({
						url: '/pagesIOSDownLoad/index?query=' + JSON.stringify(query)
					})
				}
			},
			confirm(e, key) {
				const keyMap = {
					// intentionCity: e.value.join("-"),
					workLocation: e.value[0].label === '不限' ? '' : e.value[0].label,
					companyNature: e.value[0].label === '不限' ? '' : e.value[0].label,
					recruitmentDepartment: e.value[0].label === '不限' ? '' : e.value[0].label
				}
				this.form[key] = keyMap[key];
				this[this.formPickerMap[key]] = false;
				this.operLog()
			},
			handleClick() {
				this.cityShow = true;
			},
			screeningClick(key) {
				if (this.formPickerMap[key]) {
					this[this.formPickerMap[key]] = true;
				} else {
					// 全选
					this.form.selectAll = !this.form.selectAll;
				}
			},
			handleChange(e, flag = false) {
				if (flag) {
					const state = e.length > 0 ? ['1'] : []
					this.list = this.list.map(v => ({
						...v,
						statuss: state
					}))
					if (state) {
						this.selectArr = this.list.map(v => v.id)
					} else {
						this.selectArr = []
					}
					return
				}
				this.$nextTick(() => {
					const state = (this.list.every(v => {
						return v.statuss.length > 0;
					}) ? ['1'] : [])
					this.allSelect = state
					
					const arr = this.list.filter(v => {
						if (v.statuss.length > 0) {
							return v.id
						}
					})
					this.selectArr = arr.map(v => v.id)
				})
			},
			scroll(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
		 	async sendResume(str, flag=false) {
				const data = {
				  userId: this.userInfo.userId,
				  ...this.query,
				  ids: str + ''
				}
				if(flag) {
				  try {
						const { data: datas } = await delivery(data);
						this.EduNotMeet = datas.EduNotMeet || [];
						this.majorNotMeet = datas.majorNotMeet || [];
						this.meetId = datas.meetId || [];
						this.allDelivery = true;
					} catch (err) {
						uni.showToast({
							title: err.msg,
							icon: 'none'
						})
						if (err.code == '201') {
							this.uploadModel = true
						}
					}
				  return
				}
				const res = await sendResume(data);
				this.$refs.uToast.show({
					type: 'success',
					message: res.msg
				})
				this.allDeliveryClose();
			},
			uploadModelClose() {
				this.uploadModel = false;
			},
			allDeliveryClose() {
				this.allDelivery = false;
				this.meetId = []
			},
			onDiscernHandle() {
        if (this.fileList.length !== 0) {
          return false;
        }
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera', 'album'], //从相册选择
          success: async (res) => {
            var imageSrc = res.tempFilePaths[0]
            const token = uni.getStorageSync('AccessToken');
  
            uni.showLoading({
              title: '加载中...',
              mask: true
            })
            uni.uploadFile({ //上传图片
              url: 'https://yanj.com.cn/wx/resume/upload', //开发者服务器 url
              filePath: imageSrc, //要上传文件资源的路径。
              fileType: 'image', //文件类型，image/video/audio
              name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
              header: {
                Authorization: `Bearer ${token}`
              },
              success: (res) => { //接口调用成功的回调函数
                uni.showToast({ //消息提示框
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
                this.uploadModelClose();
                uni.hideLoading();
              },
              fail: () => {
                // 接口调用失败
                uni.hideLoading();
              }
            });
          },
  
        });
      }
		},
	};
</script>

<style lang="scss" scoped>
	.bgimg {
		position: fixed;
		height: 100vh;
		width: 100vw;
		background-color: #FFFFFF;
		z-index: 3;

		.bg {
			position: absolute;

			&.one {
				width: 80rpx;
				height: 230rpx;
				left: 0;
				top: 0;
			}

			&.two {
				width: 50%;
				height: 200rpx;
				left: 0;
				bottom: 0;
			}

			&.three {
				width: 70vw;
				height: 35vh;
				right: 0;
				top: -60rpx;
			}
		}
	}

	.main {
		position: relative;
		min-height: calc(96vh - 100rpx);
		padding-top: 5vh;
		font-size: 30rpx;
		box-sizing: border-box;
		z-index: 9;

		.header {
			position: relative;
			z-index: 6;
			display: flex;
			margin-bottom: -60rpx;
			display: flex;
			justify-content: center;
			margin-left: -20rpx;

			.btn {
				margin: 0 auto;
				width: 39%;
				height: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				clip-path: polygon(0 0, 100% 0, 85% 100%, 0 100%);
				border-radius: 10rpx 0 0 10rpx;
				color: #ffffff;
				background-color: #7665f9;
				transition: all 0.3s;
				display: flex;
				justify-content: center;
				align-items: center;
				margin: 0;
				&:active {
					background-color: #bab6ff;
				}

				.icon {
					width: 50rpx;
					height: 50rpx;
				}

				&.active {
					background-color: #7665f9;
					&:active {
						background-color: #bab6ff;
					}
				}

				&:last-child {
					clip-path: polygon(15% 0, 100% 0, 97% 13%, 90% 65%, 82% 100%, 0 100%);
					margin-left: -30rpx;
					border-radius: 0rpx;
				}
			}

			.total {
				min-width: 100rpx;
				text-align: center;
				padding: 10rpx 0;
				color: #FFFFFF;
				white-space: nowrap;
			}
		}

		.center {
			position: relative;
			width: 100%;
			margin: 0 auto;
		}

		.card {
			min-height: 60vh;
			border-radius: 32rpx;
			padding: 32rpx;
			display: flex;
			flex-direction: column;
			background: rgba(238, 239, 248, 0.25);
			box-shadow: 10rpx 10rpx 20rpx rgba(236, 237, 245, 0.05);
			backdrop-filter: blur(5px);
			border-radius: 16rpx;
			padding: 100rpx 32rpx;
			box-sizing: border-box;
			clip-path: polygon(0 8%, 74% 8%, 77% 6%, 80% 2%, 83% 0, 100% 0, 100% 100%, 81% 100%, 56% 100%, 41% 100%, 18% 100%, 0 100%);

			.screeningList {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: -20rpx;
				color: #a0a0a2;

				.item {
					display: flex;

					.icon {
						width: 80rpx;
						height: 100%;
						margin-left: -40rpx;
					}

					.allSelect {
						transform: scale(0.85);
					}
				}
			}
		}

		.tbody {
			width: 100%;
			height: 85vh;
			top: 10vh;
			position: absolute;
			padding: 12rpx 32rpx;
			box-sizing: border-box;
			background: rgba(238, 239, 248, 0.25);
			box-shadow: 10rpx 10rpx 20rpx rgba(236, 237, 245, 0.05);
			backdrop-filter: blur(5px);
			border-radius: 0 0 16rpx 16rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			padding-bottom: 30rpx;

			.cardItem {
				background-color: #fff;
				border-radius: 12rpx;
				padding: 24rpx 32rpx;
				box-sizing: border-box;
				box-shadow: 10rpx 10rpx 20rpx rgba(236, 237, 245, 0.05);
				margin-top: 20rpx;

				.title {
					color: #8353eb;
					display: flex;
					justify-content: space-between;
				}

				.content2 {
					display: flex;
					flex-direction: column;
					gap: 24rpx;
					padding: 20rpx 0;
					border-bottom: 1rpx dotted #cfc9f3;

					.item {
						display: flex;
						align-items: center;

						.label {
							min-width: 150rpx;
							font-weight: 600;
						}

						&.line {
							justify-content: space-between;
						}
					}
				}

				.footer {
					padding-top: 24rpx;
					display: flex;
					justify-content: space-between;

					.textBox {
						display: flex;

						.label {
							font-weight: 600;
						}
					}

					.btn {
						width: 40%;
					}
				}
			}
		}
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}
 
	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}
 
	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		// box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		// border-radius: 10px !important;
		background: #FFFFFF !important;
	}
	.allDelivery {
		width: 600rpx;
		margin: 10rpx;
		border-radius: 8rpx;
		.list {
			max-height: 55vh;
			display: flex;
			flex-direction: column;
			gap: 10rpx;
			.item {
				.label {
					font-weight: 600;
					display: flex;
					align-items: center;
					flex-wrap: wrap;
				}
				.value {
					font-weight: 100;
				}
			}
		}
	}
	.confirmButtonbtns {
		width: 100%;
		display: flex;
		gap: 10rpx;
		margin-top: 20rpx;
	}
	.uploadModel {
		width: 600rpx;
	}
</style>